package cn.chenwx.bbsforum.service.Impl;

import cn.chenwx.bbsforum.entity.Article;
import cn.chenwx.bbsforum.mapper.ArticleMapper;
import cn.chenwx.bbsforum.service.ArticleService;
import cn.chenwx.bbsforum.service.UserService;
import cn.chenwx.bbsforum.utils.BlogJSONResult;
import cn.chenwx.bbsforum.utils.DateUtils;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service()
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    ArticleMapper articleMapper;
    @Autowired
    UserService userService;
    @Override
    public List<Article> findAllArticle(int rows, int pageNum) {
        PageHelper.startPage(pageNum,rows);
        return articleMapper.findAllArticle();
    }

    @Override
    public Article findArticleById(int id) {
        Article article = articleMapper.findArticleById(id);
        if (article.getCreatTime()!=null && article.getCreatTimeStr()==null){
            article.setCreatTimeStr(DateUtils.dateToString(article.getCreatTime(),"yyyy-MM-dd HH:mm"));
        }
        return article;
    }

    @Override
    public int addArticle(Article article) {
        return articleMapper.addArticle(article);
    }

    @Override
    public int updateArticle(Article article) {
        return articleMapper.modifyArticle(article);
    }

    @Override
    public BlogJSONResult deleteArticle(int id) {
        articleMapper.deleteArticle(id);
        return BlogJSONResult.ok();
    }

    @Override
    public int getArticle() {
        return articleMapper.getArticleNum();
    }

    @Override
    public List<Article> findArticleByTag(String tag, int rows, int pageNum) {
        PageHelper.startPage(pageNum,rows);
        return articleMapper.findAritcleByTag(tag);
    }

    @Override
    public Article findArticleByUserId(Integer id) {
        return articleMapper.findArticleByUserId(id);
    }

    @Override
    public List<Article> findAllArticles() {
        List<Article> articles=articleMapper.findAllArticle();
        for(Article article : articles){
            if (article.getCreatTime()!=null){
                article.setCreatTimeStr(DateUtils.dateToString(article.getCreatTime(),"yyyy-MM-dd HH:mm"));
            }

            article.setUsername(userService.findUserById(article.getUserId()).getUsername());

        }

        return articles ;
    }

    @Override
    public int getArticleNum() {
        return articleMapper.getArticleNum();
    }
}
